package org.amq.client.listener;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.jms.ConnectionFactory;

import org.amq.base.util.ApplicationContextHolder;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.jms.pool.PooledConnectionFactory;
import org.springframework.jms.listener.DefaultMessageListenerContainer;

public class ListenerInit {

    public static AtomicBoolean IS_CONNECTED_2_MQ = new AtomicBoolean(false);

    public static Map<String, DefaultMessageListenerContainer> container =
            new ConcurrentHashMap<String, DefaultMessageListenerContainer>();

    private ListenerInit() {
    }

    public static void stop() {
        for (DefaultMessageListenerContainer li : container.values()) {
            li.stop();
            li.destroy();
        }
        container.clear();
    }

    private static void create(String queueName, String connectionBeanName, String listenerBean, String concurrency) {
        DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer();
        ActiveMQQueue queue = new ActiveMQQueue(queueName);
        ConnectionFactory connectionFactory =
                (PooledConnectionFactory) ApplicationContextHolder.getApplicationContext().getBean(connectionBeanName);
        if (connectionFactory == null) {
            throw new RuntimeException("beanId not found,must in xml" + connectionBeanName);
        }
        listenerContainer.setConnectionFactory(connectionFactory);
        listenerContainer.setDestination(queue);

        Object listener = ApplicationContextHolder.getApplicationContext().getBean(listenerBean);
        if (listener == null) {
            throw new RuntimeException("beanId not found,must in xml" + listenerBean);
        }
        listenerContainer.setConcurrency(concurrency);
        listenerContainer.setIdleConsumerLimit(1);

        listenerContainer.setMessageListener(listener);
        listenerContainer.setCacheLevel(3);
        listenerContainer.setSessionTransacted(true);
        listenerContainer.initialize();
        listenerContainer.start();
        container.put(queueName + connectionBeanName + System.nanoTime(), listenerContainer);
    }
}
